# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from testing_support import auto_stub

from testing_support.git.repo import GitRepo
from testing_support.git.schema import GitRepoSchema


class GitRepoTestBase(auto_stub.TestCase):
  """A TestCase with a built-in GitRepoSchema and a GitRepo based on that
  schema.

  Expects a class variable REPO_SCHEMA to be a GitRepoSchema string in the form
  described by that class.

  You may also set class variables in the form COMMIT_%(commit_name)s, which
  provide the content for the given commit_name commits (this behavior can be
  overridden by overriding getRepoContent()).

  This GitRepo will appear as self.repo, and will be deleted and recreated for
  each test method in the subclass.
  """
  REPO_SCHEMA = None

  @classmethod
  def getRepoContent(cls, commit):
    return getattr(cls, 'COMMIT_%s' % commit, None)

  def assertSchema(self, schema_string):
    self.assertEqual(GitRepoSchema(schema_string).simple_graph(),
                     self.repo.to_schema().simple_graph())

  def setUp(self):
    super(GitRepoTestBase, self).setUp()
    assert self.REPO_SCHEMA is not None
    # TODO(iannucci): r_schema could be established at class-load time, using
    # a metaclass. This would enable us to only parse the schema once per
    # derived test case class.
    self.r_schema = GitRepoSchema(self.REPO_SCHEMA, self.getRepoContent)
    self.repo = GitRepo(self.r_schema)
    self.repo.git('checkout', '-f', self.repo.last_commit)

  def tearDown(self):
    try:
      self.repo.nuke()
    finally:
      super(GitRepoTestBase, self).tearDown()
